<template>
	<view class="stats-container">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 日期选择器 -->
		<view class="date-picker">
			<view class="calendar-icon">
				<text class="iconfont icon-calendar"></text>
			</view>
			<picker mode="date" :value="startDate" @change="onStartDateChange">
				<text>{{ startDate }}</text>
			</picker>
			<text class="arrow">▼</text>
			<text class="separator">~</text>
			<picker mode="date" :value="endDate" @change="onEndDateChange">
				<text>{{ endDate }}</text>
			</picker>
			<text class="arrow">▼</text>
		</view>
		<!-- 数据走势 -->
		<view class="data-trend">
			<view class="trend-header">
				<text class="title">数据走势</text>
				<view class="filter" @click="toggleChartType">
					<text>{{ chartTypes[currentChartTypeIndex] }}</text>
					<text class="arrow">▼</text>
				</view>
			</view>
			<!-- 图表区域 -->
			<view class="chart-area">
				<canvas canvas-id="statsChart" id="statsChart" class="charts"></canvas>
			</view>
		</view>
		<!-- 数据说明 -->
		<view class="data-info">
			<view class="info-header">
				<text>数据汇总</text>
				<view class="help-icon" @click="goToStatsInfo">
					<text class="iconfont icon-help">?</text>
					<text style="color: #2B85E4">数据说明</text>
				</view>
			</view>
			<!-- 数据表格 -->
			<view class="data-grid">
				<!-- 第一组：开放时间和日均收单数 -->
				<view class="grid-group">
					<view class="grid-row">
						<view class="grid-cell left">
							<text>开放时间</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.openHours }}小时</text>
						</view>
						<view class="grid-cell right">
							<text>日均收单数</text>
						</view>
					</view>
					<view class="grid-row">
						<view class="grid-cell left">
							<text>收到单数</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.receivedOrders }}</text>
						</view>
						<view class="grid-cell right">
							<text>{{ stats.avgDailyOrders }}</text>
						</view>
					</view>
				</view>
				<!-- 第二组：接单单数和接单率 -->
				<view class="grid-group">
					<view class="grid-row">
						<view class="grid-cell left">
							<text>接单单数</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.acceptedOrders }}</text>
						</view>
						<view class="grid-cell right">
							<text>接单率</text>
						</view>
					</view>
					<view class="grid-row">
						<view class="grid-cell left">
							<text>接单金额</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.acceptedAmount }}元</text>
						</view>
						<view class="grid-cell right">
							<text>{{ stats.acceptanceRate }}%</text>
						</view>
					</view>
				</view>
				<!-- 第三组：成交单数和成交率 -->
				<view class="grid-group">
					<view class="grid-row">
						<view class="grid-cell left">
							<text>成交单数</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.completedOrders }}</text>
						</view>
						<view class="grid-cell right">
							<text>成交率</text>
						</view>
					</view>
					<view class="grid-row">
						<view class="grid-cell left">
							<text>成交金额</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.completedAmount }}元</text>
						</view>
						<view class="grid-cell right">
							<text>{{ stats.completionRate }}%</text>
						</view>
					</view>
				</view>
				<!-- 第四组：取消单数和退款率 -->
				<view class="grid-group">
					<view class="grid-row">
						<view class="grid-cell left">
							<text>取消单数</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.cancelledOrders || 0 }}</text>
						</view>
						<view class="grid-cell right">
							<text>退款率</text>
						</view>
					</view>
					<view class="grid-row">
						<view class="grid-cell left">
							<text>退款金额</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.refundAmount || 0 }}元</text>
						</view>
						<view class="grid-cell right">
							<text>{{ stats.refundRate || 0 }}%</text>
						</view>
					</view>
				</view>
				<!-- 第五组：成交用户和复购率 -->
				<view class="grid-group">
					<view class="grid-row">
						<view class="grid-cell left">
							<text>成交用户</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.completedUsers || 0 }}</text>
						</view>
						<view class="grid-cell right">
							<text>复购率</text>
						</view>
					</view>
					<view class="grid-row">
						<view class="grid-cell left">
							<text>复购用户</text>
						</view>
						<view class="grid-cell center">
							<text>{{ stats.repurchaseUsers || 0 }}</text>
						</view>
						<view class="grid-cell right">
							<text>{{ stats.repurchaseRate || 0 }}%</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import TechNavBar from '@/components/tech-nav-bar.vue'
	import * as echarts from 'echarts'
	import NavBar from '@/components/nav-bar/nav-bar.vue'
	export default {
		components: {
			TechNavBar,
			NavBar
		},
		data() {
			return {
				startDate: '',
				endDate: '',
				stats: {
					openHours: 0,
					receivedOrders: 0,
					acceptedOrders: 0,
					acceptedAmount: 0,
					completedOrders: 0,
					completedAmount: 0,
					cancelledOrders: 0,
					refundAmount: 0,
					completedUsers: 0,
					repurchaseUsers: 0,
					invitedUsers: 0,
					firstTimeUsers: 0,
					avgDailyOrders: 0,
					acceptanceRate: 0,
					completionRate: 0,
					refundRate: 0,
					repurchaseRate: 0
				},
				chartTypes: ['接单单数', '接单金额', '成交单数', '成交金额'],
				chartTypeKeys: ['acceptedOrders', 'acceptedAmount', 'completedOrders', 'completedAmount'],
				currentChartTypeIndex: 0,
				chartData: {
					dates: [],
					values: []
				},
				myChart: null,
				technicianId: null,
				loading: false
			}
		},
		methods: {
			// 初始化日期范围（默认为前11天到今天，共12天）
			initDateRange() {
				const today = new Date();
				const elevenDaysAgo = new Date();
				elevenDaysAgo.setDate(today.getDate() - 11); // 获取12天的数据（包括今天）

				this.endDate = this.formatDate(today);
				this.startDate = this.formatDate(elevenDaysAgo);
			},

			// 格式化日期为 YYYY-MM-DD
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			onStartDateChange(e) {
				const newStartDate = e.detail.value;

				// 验证开始日期不能大于结束日期
				if (newStartDate > this.endDate) {
					uni.showToast({
						title: '开始日期不能大于结束日期',
						icon: 'none'
					});
					return;
				}

				this.startDate = newStartDate;
				this.fetchStats(); // 获取新的统计数据
			},

			onEndDateChange(e) {
				const newEndDate = e.detail.value;

				// 验证结束日期不能小于开始日期
				if (newEndDate < this.startDate) {
					uni.showToast({
						title: '结束日期不能小于开始日期',
						icon: 'none'
					});
					return;
				}

				this.endDate = newEndDate;
				this.fetchStats(); // 获取新的统计数据
			},

			// 获取技师ID
			getTechnicianId() {
				// 从本地存储或全局状态获取技师ID
				// 这里假设技师ID存储在本地存储中
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo && userInfo.techId) {
					this.technicianId = userInfo.techId;
				} else {
					// 如果没有技师ID，可能需要跳转到登录页面
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
				}
			},

			// 获取统计数据
			fetchStats() {
				if (!this.startDate || !this.endDate || !this.technicianId) {
					return;
				}

				// 验证日期范围
				if (this.startDate > this.endDate) {
					uni.showToast({
						title: '开始日期不能大于结束日期',
						icon: 'none'
					});
					return;
				}

				this.loading = true;

				// 显示加载中
				uni.showLoading({
					title: '加载中...'
				});

				// 调用接口获取数据
				uni.request({
					url: `${uni.$config.baseUrl}/stats/stats/getStatsByDateRange`,
					method: 'GET',
					data: {
						startDate: this.startDate,
						endDate: this.endDate,
						technicianId: this.technicianId
					},
					success: (res) => {
						if (res.data.code === 200) {
							const data = res.data.data;

							// 更新统计数据
							if (data.stats) {
								this.stats = {
									...this.stats,
									...data.stats
								};

								// 缓存图表数据以便切换图表类型时使用
								if (data.chartData) {
									uni.setStorageSync('statsChartData', data.chartData);
									this.updateChartDataFromApi(data.chartData);
								}
							}
						} else {
							uni.showToast({
								title: res.data.msg || '获取数据失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('获取统计数据失败', err);
						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
						this.loading = false;

						// 更新图表
						this.updateChart();
					}
				});
			},

			// 从API响应更新图表数据
			updateChartDataFromApi(apiChartData) {
				if (!apiChartData) return;

				// 获取当前选中的图表类型对应的键
				const currentTypeKey = this.chartTypeKeys[this.currentChartTypeIndex];

				// 如果API返回的数据包含当前选中的图表类型数据
				if (apiChartData.dates && apiChartData[currentTypeKey]) {
					this.chartData.dates = apiChartData.dates;
					this.chartData.values = apiChartData[currentTypeKey];
				}
			},

			goToStatsInfo() {
				uni.navigateTo({
					url: '/pages/technician/statsinfo'
				});
			},

			toggleChartType() {
				this.currentChartTypeIndex = (this.currentChartTypeIndex + 1) % this.chartTypes.length;

				// 从缓存中获取图表数据
				const apiChartData = uni.getStorageSync('statsChartData');
				if (apiChartData) {
					this.updateChartDataFromApi(apiChartData);
					this.updateChart();
				} else {
					// 如果没有缓存数据，重新获取
					this.fetchStats();
				}
			},

			initChart() {
				// 获取 DOM 节点
				const chartDom = document.getElementById('statsChart');

				if (!chartDom) {
					console.error('找不到图表DOM元素');
					return;
				}

				// 初始化图表
				this.myChart = echarts.init(chartDom);

				// 更新图表
				this.updateChart();
			},

			updateChart() {
				if (!this.myChart) return;

				// 获取当前选中的图表类型
				const currentType = this.chartTypes[this.currentChartTypeIndex];
				const currentTypeKey = this.chartTypeKeys[this.currentChartTypeIndex];
				const isAmountType = currentTypeKey.includes('Amount');

				// 设置选项
				const option = {
					title: {
						text: currentType + '走势',
						left: 'center',
						textStyle: {
							fontSize: 14
						}
					},
					tooltip: {
						trigger: 'axis',
						formatter: (params) => {
							const param = params[0];
							let value = param.value;

							// 如果是金额，添加单位
							if (isAmountType) {
								value = value + '元';
							}

							return param.name + ': ' + value;
						},
						axisPointer: {
							type: 'cross',
							label: {
								backgroundColor: '#6a7985'
							}
						}
					},
					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						boundaryGap: false,
						data: this.chartData.dates,
						axisLabel: {
							interval: 0,
							rotate: 30
						}
					},
					yAxis: {
						type: 'value',
						axisLabel: {
							formatter: (value) => {
								// 如果是金额，可以格式化显示
								if (isAmountType) {
									return value.toFixed(0);
								}
								return value;
							}
						}
					},
					// 添加数据缩放组件，方便用户查看长时间范围的数据
					dataZoom: [{
							type: 'inside',
							start: 0,
							end: 100
						},
						{
							start: 0,
							end: 100
						}
					],
					// 添加标记点，显示最大值和最小值
					series: [{
						name: currentType,
						type: 'line',
						stack: '总量',
						data: this.chartData.values,
						smooth: true,
						areaStyle: {
							color: {
								type: 'linear',
								x: 0,
								y: 0,
								x2: 0,
								y2: 1,
								colorStops: [{
										offset: 0,
										color: 'rgba(43, 133, 228, 0.3)'
									},
									{
										offset: 1,
										color: 'rgba(43, 133, 228, 0.1)'
									}
								]
							}
						},
						itemStyle: {
							color: '#2B85E4'
						},
						lineStyle: {
							width: 2,
							color: '#2B85E4'
						},
						// 添加标记点，显示最大值和最小值
						markPoint: {
							data: [{
									type: 'max',
									name: '最大值'
								},
								{
									type: 'min',
									name: '最小值'
								}
							]
						},
						// 添加平均线
						markLine: {
							data: [{
								type: 'average',
								name: '平均值'
							}]
						},
						// 强调当前鼠标悬停的数据点
						emphasis: {
							itemStyle: {
								color: '#ff7f50',
								borderWidth: 3,
								shadowBlur: 10,
								shadowColor: 'rgba(0, 0, 0, 0.3)'
							}
						}
					}]
				};

				// 应用配置
				this.myChart.setOption(option);

				// 添加图表点击事件，显示详细信息
				this.myChart.off('click');
				this.myChart.on('click', (params) => {
					const date = params.name;
					const value = params.value;
					const formattedValue = isAmountType ? value + '元' : value;

					uni.showToast({
						title: `${date}: ${currentType} ${formattedValue}`,
						icon: 'none',
						duration: 2000
					});
				});
			}
		},
		onLoad() {
			// 初始化日期范围
			this.initDateRange();

			// 获取技师ID
			this.getTechnicianId();

			// 获取统计数据
			this.fetchStats();
		},
		mounted() {
			this.initChart();
		},
		onReady() {
			// 在页面渲染完成后初始化图表
			setTimeout(() => {
				this.initChart();
			}, 300);
		},
		onResize() {
			// 窗口大小变化时重新调整图表大小
			if (this.myChart) {
				this.myChart.resize();
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.fetchStats();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		}
	}
</script>

<style lang="scss" scoped>
	.stats-container {
		min-height: 100vh;
		background: #F5F5F5;
	}

	.date-picker {
		background: #FFFFFF;
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.calendar-icon {
			margin-right: 10rpx;
			color: #2B85E4;
		}

		.separator {
			margin: 0 20rpx;
			color: #999;
		}

		.arrow {
			margin-left: 10rpx;
			color: #999;
			font-size: 24rpx;
		}

		text {
			color: #333;
			font-size: 28rpx;
		}
	}

	.data-trend {
		background: #FFFFFF;
		padding: 20rpx;
		margin-bottom: 20rpx;

		.trend-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.title {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
			}

			.filter {
				display: flex;
				align-items: center;
				color: #666;
				font-size: 28rpx;
				background-color: #f5f5f5;
				padding: 6rpx 16rpx;
				border-radius: 30rpx;

				.arrow {
					margin-left: 10rpx;
					font-size: 24rpx;
				}
			}
		}

		.chart-area {
			height: 300px;
			width: 100%;

			.charts {
				width: 100%;
				height: 100%;
			}
		}
	}

	.data-info {
		background: #FFFFFF;
		padding: 20rpx;
		margin-bottom: 20rpx;

		.info-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			text {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
			}

			.help-icon {
				display: flex;
				align-items: center;
				color: #999;
				font-size: 24rpx;

				.icon-help {
					margin-right: 6rpx;
					font-size: 28rpx;
					color: #2B85E4;
				}
			}
		}

		.data-grid {
			width: 100%;

			.grid-group {
				margin-bottom: 20rpx;
				border: 1rpx solid #eee;
				border-radius: 8rpx;
				overflow: hidden;

				&:last-child {
					margin-bottom: 0;
				}
			}

			.grid-row {
				display: flex;

				&:first-child {
					border-bottom: 1rpx solid #eee;
				}
			}

			.grid-cell {
				flex: 1;
				padding: 24rpx 10rpx;
				font-size: 28rpx;
				color: #333;
				display: flex;
				align-items: center;

				&.left {
					justify-content: flex-start;
					border-right: 1rpx solid #eee;
				}

				&.center {
					justify-content: flex-end;
					border-right: 1rpx solid #eee;
				}

				&.right {
					justify-content: flex-end;
					background-color: #f8f8ff;
				}
			}
		}
	}
</style>